package com.ruijie.acl.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.faces.model.SelectItem;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;

import com.ruijie.acl.AclPlanParameters;
import com.ruijie.acl.TimeRange;
import com.ruijie.acl.service.DeviceTimeRangeService;
import com.ruijie.acl.service.TimeRangeService;
import com.ruijie.acl.type.AclPlanTypeEnum;
import com.ruijie.acl.utils.AclUtil;
import com.ruijie.acl.web.config.Constants;
import com.ruijie.emp.device.Device;
import com.ruijie.foundation.bo.EntityObject;
import com.ruijie.foundation.dao.support.Page;
import com.ruijie.foundation.service.Repository;
import com.ruijie.foundation.web.intercept.AddSuccessInfo;

/**
 * <p>
 * Title: ACL时间段管理Action类

 * </p>
 * <p>
 * Description:
 * </p>
 * <p>
 * 为ACL时间段管理模块提供页面数据的显示、获取和页面的跳转。

 * </p>
 * <p>
 * Copyright: Copyright (c) 2008
 * </p>
 * <p>
 * Company: Ruijie Co., Ltd.
 * </p>
 * <p>
 * Create Time: 
 * </p>
 * <p>
 * </p>
 * <p>
 * Update Time:
 * </p>
 * <p>
 * Updater:
 * </p>
 * <p>
 * Update Comments:
 * </p>
 * @author ASAI
 */

@Name("timeRangeAction")
@Scope(ScopeType.CONVERSATION)
@AddSuccessInfo
public class TimeRangeAction extends AclPlanBaseAction {
	
	@In("#{timeRangeService}")
	private TimeRangeService timeRangeService;
	
	@In("#{deviceTimeRangeService}")
	private DeviceTimeRangeService deviceTimeRangeService;
	
	@In("#{timeInfoAction}")
	private TimeInfoAction timeInfoAction;
	
	private TimeRange model;
	
	private TimeRange criteria = new TimeRange();

	//记录哪些时间段与设备关联f
	private String relationTimeRange;

	
	/**
	 * 是否已经被设备关联。
	 * 
	 * @return 是否关联
	 */
	public boolean isRelativeDevice(TimeRange timeRange) {
		return deviceTimeRangeService.isExistDeviceTimeRange(null, timeRange);
	}
	
	
	
	public String toTimeAbsolutePage(){
		return "/acl/timeAbsoluteAdd.seam";
	}
	
	@SuppressWarnings("unchecked")
	@Override
	protected Repository getRepository() {
		return this.timeRangeService;
	}
	
	/** 
     * <p>Description:  批量删除操作 </p>
     * <p>Create Time: 2008-11-3   </p>
     * @author lusl
     */
	@SuppressWarnings("unchecked")
	@Override
    public void delete() {
		List<AclPlanParameters> paramList = new ArrayList<AclPlanParameters>();
		Map<Device, String[]> map = new HashMap<Device, String[]>();
		for(Long id:getIds()){
			TimeRange timeRange = timeRangeService.get(id);	
			/*如果与设备关联*/
			if(timeRangeService.isRelated2Device(timeRange)){
				List<Device> deviceList = timeRangeService.getDevices(timeRange);
				for(Device device : deviceList){
					/*如果重复则合并名字*/
					if(map.containsKey(device)){
						//合并时间段名称
						map.get(device)[0] += "," + AclUtil.escapeSpecialString(timeRange.getName());
					}else{
						String[] strArr = new String[1];
						strArr[0] = AclUtil.escapeSpecialString(timeRange.getName());
						map.put(device, strArr);
					}
				}
			}
		}
		/*遍历map加入paramList*/
		Iterator iterator = map.entrySet().iterator();
		while(iterator.hasNext()){
			Map.Entry entry = (Map.Entry)iterator.next();
			String[] strArr = (String[])entry.getValue();
			Device device = (Device)entry.getKey();
			paramList.add(deleteDeployment(device,strArr[0]));
		}

        if(paramList.size()>0){
        	this.setTaskCode(Constants.ACL_DEPLOY_ACTION_TASK_CODE_DELETE_TIMERANGE);
       	 	super.saveAclPlanParameters(paramList);
        } 
        
        super.delete();
    }
	
	/**
	 * 删除时间段时的重新部署
	 * @param id timeRangeId
	 */
	public AclPlanParameters deleteDeployment(Device device,String timeRangeString){
		AclPlanParameters parameters = new AclPlanParameters();
		parameters.setTimeRanges(timeRangeString);
		parameters.setDevice(device);
		parameters.setDealType(AclPlanTypeEnum.DeleteTimeRange.toString());
		
		return parameters;
	}
	
	/**
	 * 时间段详细界面的多设备部署
	 * @param timeRange 时间段
	 */
	public void reDeploy(){
		// 取得数据库最新的信息。
		TimeRange timeRange = timeRangeService.get(this.getModel().getId());
		List<AclPlanParameters> paramList = new ArrayList<AclPlanParameters>();
		List<Device> deviceList = timeRangeService.getDevices(timeRange);
		for(Device device:deviceList){
			AclPlanParameters aclparameters = new AclPlanParameters();
			aclparameters.setTimeRanges(String.valueOf(timeRange.getId()));
			aclparameters.setDevice(device);
			aclparameters.setDealType(AclPlanTypeEnum.ReDeployTimeRange.toString());
			
			paramList.add(aclparameters);
		}
		this.setTaskCode(Constants.ACL_DEPLOY_ACTION_TASK_CODE_REDEPLOY_TIMERANGE);
		super.saveAclPlanParameters(paramList);
		timeRange.setIsChanged(false);
		timeRangeService.update(timeRange);
		
		// 更新所有不一致设备全部时间段副本。
//		List<AclDeviceTimeRange> aclDeviceTimeRangeList = deviceTimeRangeService.getAclDeviceByChanged(timeRange);
//		for(AclDeviceTimeRange aclDeviceTimeRange : aclDeviceTimeRangeList){
//			timeRangeService.saveSameWithAclDevice(timeRange,aclDeviceTimeRange.getAclDevice(),null);
//		}
//		deviceTimeRangeService.updateChangedByTimeRange(timeRange);
		this.setModel(timeRange);
		timeInfoAction.setParentEntity(timeRange);
		addGlobalI18nMessage("acl_redeploy_plan_create_success");
	}

	@Override
	protected String getAddPage() {
		return "/acl/timeRangeAdd.seam";
	}

	@Override
	public EntityObject getCriteria() {
		return this.criteria;
	}

	@Override
	protected String getDetailPage() {
		return "/acl/timeRangeDetail.seam";
	}

	@Override
	protected String getListPage() {
		return "/acl/timeRangeIndex.seam";
	}

	@Override
	public EntityObject getModel() {
		model.setDeleteFlg(false);
		return this.model;
	}

	@Override
	protected String getUpdatePage() {
		return "/acl/timeRangeEdit.seam";
	}

	@Override
	public void resetModel() {
		this.model = new TimeRange();
		this.model.setIsChanged(false);
	}
	
	@SuppressWarnings("unchecked")
	protected Page pagedQuery(EntityObject criteria, int page, int pageSize) {		
		Page result=timeRangeService.pageQueryByTimeRange(((TimeRange) criteria), page, pageSize);
		return result;
	}

	@SuppressWarnings("unchecked")
	public String getRelationTimeRange() {
		if(this.currentPage==null)return null;
		List<TimeRange> trs=(List<TimeRange>)this.currentPage.getResult();
		StringBuffer sb=new StringBuffer();
		for(TimeRange tr:trs){
			if(this.timeRangeService.isRelated2Device(tr)){
				sb.append(tr.getName()).append(" ");
			}
		}
		if(sb.length()>0){
			relationTimeRange=sb.substring(0, sb.length()-1);
		}else{
			relationTimeRange="";
		}
		return relationTimeRange;
	}

	public void setRelationTimeRange(String relationTimeRange) {
		this.relationTimeRange = relationTimeRange;
	}

	@Override
	public void setCriteria(EntityObject criteria) {
		this.criteria=(TimeRange)criteria;
	}

	@Override
	public void setModel(EntityObject model) {
		this.model=(TimeRange)model;
	}

	public List<SelectItem> getSelectItems(){
		List<SelectItem> resultList = new ArrayList<SelectItem>(); 
		List<TimeRange> list = timeRangeService.getWithoutAclDevice();
		if (list != null && list.size() > 0){
			for(TimeRange entity : list){
				resultList.add(new SelectItem(entity, entity.getName()));
			}
		}
		return resultList;
	}
	
	public void resetNewestModel(){
		try{
			TimeRange newestModel = timeRangeService.get(this.model.getId());
			this.setModel(newestModel);
			timeInfoAction.setParentEntity(newestModel);
		}catch(Exception ex){
			//
		}
	}
	
	//-------------modify by sinyee 2010-10-22 being----------------

	public String toAddPageBlank(){
		this.toAddPage();
		return null;
	}
	
	@AddSuccessInfo
	public String addEntity(){
		this.add();
		return null;
	}

	public String toUpdatePageBlank(EntityObject model){
		this.toUpdatePage(model);
		return null;
	}
	
	@AddSuccessInfo
	public String updateEntity(){
		this.update();
		return null;
	}
	
	public String toDetailPageBlank(EntityObject model){
		this.toDetailPage(model);
		return null;
	}
	
	//--------------modify by sinyee 2010-10-22 end----------------
	
	
}
